package com.itheima.reggie.controller;

import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

//员工管理模块
@RestController
public class EmployeeController {

    //依赖注入
    @Autowired
    private EmployeeService employeeService;

    //员工登录
    @PostMapping("/employee/login")
    public ResultInfo login(@RequestBody Map<String, String> param , HttpSession session) {
        // 1.接收参数
        String username = param.get("username");
        String password = param.get("password");
        // 2.调用service
        ResultInfo resultInfo = employeeService.login(username,password);
        //3.判断登录是否成功
        if (resultInfo.getCode()==1) {
            //登录成功
          session.setAttribute(Constant.SESSION_EMPLOYEE,resultInfo.getData());
        }
        //4.返回结果
        return resultInfo;
    }

    // 员工退出
    @PostMapping("/employee/logout")
    public ResultInfo logout(HttpSession session) {
        //清理session
        session.invalidate();
        //返回结果
        return ResultInfo.success();
    }

    //员工列表
    @GetMapping("/employee/find")
    //1. 接受请求参数
    public ResultInfo findList(String name) {
        //2. 调用service
        List<Employee> employeeList = employeeService.findList(name);
        //3. 封装并返回
        return ResultInfo.success(employeeList);
    }

    //新增员工
    @PostMapping("/employee")
    // 1.接收前端请求参数
    public ResultInfo save(@RequestBody Employee employee) {
        //调用service
        employeeService.save(employee);

        //返回成功
        return ResultInfo.success();
    }

    // 员工信息回显
    @GetMapping("/employee/{id}")
    // 1.接收前端传来的参数
    public ResultInfo findById(@PathVariable Long id) {
        // 2.调用service
        Employee employee = employeeService.findById(id);
        // 3.返回结果
        return ResultInfo.success(employee);
    }

    //修改员工信息
    @PutMapping("/employee")
    // 1.接收前端传来的参数
    public ResultInfo updateById(@RequestBody Employee employee) {
        // 2.调用service
        employeeService.updateById(employee);
        // 3.返回结果
        return ResultInfo.success();
    }
}
